package org.example.ratelimit2.impl;

import org.example.ratelimit2.MyRateLimiter;

public class LeakyBucketRateLimiter implements MyRateLimiter {

    private final long capacity;

    private final long permitsPerSecond;

    /**
     * 剩余水量
     */
    private long leftWater;

    /**
     * 上次注入时间
     */
    private long timeStamp = System.currentTimeMillis();

    public LeakyBucketRateLimiter(long capacity, long permitsPerSecond) {
        this.capacity = capacity;
        this.permitsPerSecond = permitsPerSecond;
    }

    @Override
    public synchronized boolean tryAcquire() {
        long nowTs = System.currentTimeMillis();
        leftWater = Math.max(0, leftWater - ((nowTs - timeStamp) / 1000 * permitsPerSecond));
        timeStamp = nowTs;
        if (leftWater < capacity) {
            leftWater++;
            return true;
        }
        // 容器满了，直接丢弃
        return false;
    }
}
